package com.dfec.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.spi.DirStateFactory.Result;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSON;
import com.dfec.model.Msg;
import com.dfec.model.User;
import com.dfec.service.IUserService;
import com.dfec.service.imp.UserServiceImp;
import com.dfec.utils.Consists;
import com.dfec.utils.ResponseUtil;
import com.mysql.jdbc.log.Log;

/**
 * Servlet implementation class WangEditorImgUpload
 * 
 * filepath 文件的存放路径
 * myFileName 上传文件名称
 */

@WebServlet(description = "文件上传", urlPatterns = { "/upload" })
@MultipartConfig(location = "C://",//文件存放路径，指定的目录必须存在，否则会抛异常  
 maxFileSize =1024*1024*1024,//最大上传文件大小,经测试应该是字节为单位  
 fileSizeThreshold = 1024*1024,//当数据量大于该值时，内容将被写入文件。（specification中的解释的大概意思，不知道是不是指Buffer size），大小也是已字节单位  
 maxRequestSize =  1024*1024*1024 //针对该 multipart/form-data 请求的最大数量，默认值为 -1，表示没有限制。以字节为单位。 
)
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String fileNameExtractorRegex = "filename=\".+\"";  
	String filepath="uploadfiles/";
	private String url="url";
	private String msg_info="msg";
	private String up_ok="up_ok";
	IUserService is=null;
	Map<String, Object> fileName=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUpload() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		    List<Object> list=new ArrayList<>();
	        Msg msg=new Msg();
	        filepath="uploadfiles/";
	        try {
	        Part part=request.getPart("myFileName");
	        String user_phone=request.getParameter("user_phone");
	         filepath+=request.getParameter("filepath");
				//遍历所有的表单内容，将表单中的文件写入上传文件目录  
	            //从Part的content-disposition中提取上传文件的文件名  
	          fileName = getFileName(request, part);
	         if((boolean) fileName.get(up_ok)) {
	        	 msg.setCode(Consists.Error_Code_OK);
	        	 msg.setMsg(fileName.get(msg_info).toString());
	        	 //保存头像
	        	 if (user_phone!=null) {
	        		 if(is==null) {
	        			 is=new UserServiceImp(); 
	        		 }
	        			 //保存用户头像
						is.updateUserIcon(new User(user_phone,""), fileName.get(url).toString());
				 }
	         }
	        } catch (Exception e) {
				// TODO Auto-generated catch block
				 msg.setCode(Consists.Error_Code_ServerError);
	        	 msg.setMsg(e.getMessage());
			}
	        
	        list.add(msg);
	        list.add(fileName);
	        ResponseUtil.sendScript(response, JSON.toJSONString(list));
	}
	 /** 
     * 从Part的Header信息中提取上传文件的文件名 
     * @param part 
     * @return  上传文件的文件名，如果如果没有则返回null 
     */  
	  private Map<String, Object> getFileName(HttpServletRequest request,Part part){  
		  Map<String, Object> map=new HashMap<>();
          //获取header信息中的content-disposition，如果为文件，则可以从其中提取出文件名  
          String cotentDesc = part.getHeader("content-disposition");  
          
          String fileName = null;  
          Pattern pattern = Pattern.compile(fileNameExtractorRegex);  
          Matcher matcher = pattern.matcher(cotentDesc);  
          if(matcher.find()){  
              fileName = matcher.group();  
              fileName = fileName.substring(10, fileName.length()-1);  
          }  
//          System.out.println(fileName);
          String  result =System.currentTimeMillis()+"."+fileName.split("\\.")[1];
          String fileDir=getServletContext().getRealPath(filepath);
          File  file= new File(fileDir);
          //目录不存在，创建
          if(!file.exists()) file.mkdirs();
          
		  String realPath =fileDir +"/"+ result;
//	        // 将文件写入指定路径下
	        try {
				part.write(realPath);
//				map.put(url, "http://"+request.getLocalAddr()+":"+request.getLocalPort()+request.getContextPath()+"/" + filepath +"/" + result);
				map.put(url, "/" + filepath +"/" + result);
				map.put(msg_info,  "上传成功");
				map.put(up_ok, true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				map.put(up_ok, false);
				map.put(msg_info,  "发生错误");
			}
          return map;  
      }  

}
